import React, { Component } from 'react';
import MyEchart from '@/components/MyEcharts';
import EmptyData from '@/components/EmptyData';
import CardWrapper from '../../card-wrapper';
import getPieOption from '../options/pie';
import getBarOption from '../options/labelBar';
import { Table, Select, Tooltip, Pagination, Loading, Input } from '@knownsec/react-component';
import { Link } from 'react-router-dom';
import { getGroupList, getGroupPercent, getTopData } from '~/API';
import moment from 'moment';
import './index.less';
import RuleTable from '@/components/RuleTable';
import CopyText from '@/components/copy';
import cn from 'classnames';
import { filterNull } from '@/utils';

const info = localStorage.info ? JSON.parse(localStorage.info).modules : [];
const SelectOption = Select.Option;
class Vul extends Component {
  constructor(props) {
    super(props);
    this.state = {
      target_group_name: '',
      dataList: [],
      topXlist: [],
      topYlist: [],
      page: 1,
      limit: 10,
      total: 0,
      loading: false,
      queryVal:{target_name:'',target_url:''},
      noChangeNum: 0,
      changeNum: 0,
    };
  }
  getVulSiteList = () => {
    let columns = [
      {
        title: '业务系统',
        dataIndex: 'target_url',
        render: (e, row) => {
          const name = row.target_name ? row.target_name : row.target_title;
          return (
            <Tooltip
              overlay={
                <>
                  <p>
                    业务系统：
                    <CopyText text={e} />
                  </p>
                  <p>业务系统名称：{name || '暂未设置'}</p>
                </>
              }
              placement="topLeft"
            >
              <div>
                <Link
                  className="hrefName"
                  to="#"
                  onClick={() => {
                    window.open(e);
                  }}
                >
                  {e}
                </Link>
                <div
                  className="targetName"
                  style={{ color: name ? '#2A2B31' : '#ccc' }}
                  onClick={() => {
                    const random = Math.random();
                    this.changeName(row);
                  }}
                >
                  {name || '点击设置业务系统名称'}
                </div>
              </div>
            </Tooltip>
          );
        },
      },
      {
        title: '文本变更地址',
        dataIndex: 'text',
        className: 'widthsm',
        render: (value, row) => row.change_check.text,
      },
      {
        title: '结构变更地址',
        dataIndex: 'structure',
        className: 'widthsm',
        render: (value, row) => row.change_check.structure,
      },
      {
        title: '资源变更地址',
        dataIndex: 'resource',
        className: 'widthsm',
        render: (value, row) => row.change_check.resource,
      },
      {
        title: '最近监测时间',
        dataIndex: 'ended_at',
        render: (value) => {
          const time = value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-';
          return (
            <Tooltip
              overlay={
                <>
                  <p>最近监测时间：{time}</p>
                </>
              }
              placement="topLeft"
            >
              <div>{time}</div>
            </Tooltip>
          );
        },
      },
      {
        title: '预计下次监测时间',
        dataIndex: 'next_start_at',
        render: (value) => {
          const time = value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-';
          return (
            <Tooltip
              overlay={
                <>
                  <p>预计下次监测时间：{time}</p>
                </>
              }
              placement="topLeft"
            >
              <div>{time}</div>
            </Tooltip>
          );
        },
      },
      {
        title: '操作',
        dataIndex: 'option',
        className: 'widthsm',
        render: (value, _data) => (
          <>
            <a
              href={`/#/dashboard?sid=${_data.task_session_id}&id=${_data.target_id}&type=change_check`}
              target="_blank"
              className="main-color"
            >
              查看报表
            </a>
          </>
        ),
      },
    ];
    return columns;
  };
  changeName(row) {
    var _this = this;
    _this.props.change(row, _this.props.createForm, function (e) {
      if (e) {
        _this.getRiskList();
      }
    });
  }
  onSearchChange = (page) => {
    var _this = this;
    if (page&&page.page) {
      _this.setState(
        {
          page: page.page,
          limit: page.limit,
        },
        function () {
          _this.getRiskList();
        }
      );
    } else {
      _this.setState(
        {
          page: 1,
          limit: 10,
        },
        function () {
          _this.getRiskList();
        }
      );
    }
  };
  getRiskList() {
    this.setState({ loading: true });
    const {target_name,target_url}=this.state.queryVal
    const data=filterNull({ page: this.state.page, limit: this.state.limit,target_name, target_url})
    getGroupList({
      type: 'change_check',
      id: this.props.id,
      data,
    }).then((res) => {
      this.setState({ loading: false });
      if (res.status === 'success') {
        this.setState({
          dataList: res.data.data,
          total: res.data.total,
          target_group_name: res.data.target_group_name,
        });
      }
    });
  }
  getTop() {
    this.setState({ loading: true });
    getTopData({ type: 'change_check', id: this.props.id }).then((res) => {
      let x = [],
        y = [];
      if (res.status === 'success') {
        res.data.top.forEach((item) => {
          const xurl = item.target_url || '--';
          const xname = item.target_name ? item.target_name : item.target_title || '--';
          let a = { value: xurl + '||%%' + xname || '' };
          x.push(a);
          y.push(item.count || 0);
        });
      }
      this.setState({ topXlist: x, topYlist: y, loading: false });
    });
  }
  getpercent() {
    this.setState({ loading: true });
    getGroupPercent({ type: 'change_check', id: this.props.id }).then((res) => {
      this.setState({ loading: false });
      if (res.status === 'success') {
        let sdata = {};
        res.data.statistics.forEach((item) => {
          sdata[item.name] = item.target_count;
        });
        this.setState({ changeNum: sdata.LOW||0, noChangeNum: sdata.safe });
      }
    });
  }
  componentDidMount() {
    this.getRiskList();
    this.getpercent();
    this.getTop();
  }
  render() {
    let siteVulPie = [
      {
        name: '未变更',
        value: this.state.noChangeNum,
        color: ['#11AB4E', '#48D796'],
      },
      {
        name: '有变更',
        value: this.state.changeNum,
        color: ['#F5DDA3', '#FF7777'],
      },
    ];
    let siteVulPieOption = getPieOption(siteVulPie, true);

    let highVulSiteTop10Data = {
      x: this.state.topXlist,
      y: this.state.topYlist,
      color: [['#FF0000', '#FF8A8A']],
      transpose: true,
      limitXLabelLength: 10,
    };
    let highVulSiteTop10Option = getBarOption(highVulSiteTop10Data);
    const updateTime = new Date();
    let vulSiteList = this.getVulSiteList();
    return (
      <div className="tm-vul">
        <div className="filter">
          <label className="targetName">任务组名称：{this.state.target_group_name || '--'}</label>
          <label>更新时间：{moment(updateTime).format('YYYY-MM-DD HH:mm:ss')}</label>
        </div>
        <div className="state">
          <Loading show={this.state.loading} label="" />
          <CardWrapper title="业务系统篡改占比" className="site-vul-pie">
            {siteVulPieOption ? (
              <MyEchart option={siteVulPieOption}></MyEchart>
            ) : (
              <EmptyData size="small" />
            )}
          </CardWrapper>
          <CardWrapper title="业务系统篡改 TOP 5" className="site-vul-top10">
            {this.state.topXlist.length ? (
              <MyEchart option={highVulSiteTop10Option}></MyEchart>
            ) : (
              <EmptyData size="small" />
            )}
          </CardWrapper>
        </div>
        <CardWrapper title="业务系统篡改监测列表" className="vul-site-list">
          <div className="searchTool">
          <Input
            pro
            placeholder="搜索业务系统名称"
            value={this.state.queryVal.target_name}
            search
            className={cn('search-button')}
            onSearch={(e) => {
              this.onSearchChange({ target_name: e.value });
            }}
            clear
            onChange={(value) => {
              this.setState({queryVal:{...this.state.queryVal,target_name:value.value}})
              if (!value.e) {
              this.onSearchChange();
                return;
              }
            }}
          ></Input>
          <Input
            pro
            placeholder="搜索业务系统地址"
            value={this.state.queryVal?.target_url}
            search
            className={cn('search-button')}
            onSearch={(e) => {
              this.onSearchChange({ target_url: e.value });
            }}
            clear
            onChange={(value) => {
               this.setState({queryVal:{...this.state.queryVal,target_url:value.value}})
              if (!value.e) {
              this.onSearchChange();
                return;
              }
            }}
          ></Input>
          </div>
       
          {info.includes('vul') ? (
            <Table
              columns={vulSiteList}
              tableLoading={this.state.loading}
              loadingLabel=""
              data={this.state.dataList}
            ></Table>
          ) : (
            <RuleTable columns={vulSiteList} data={this.state.dataList}></RuleTable>
          )}
          {info.includes('vul') && this.state.total > 10 && (
            <Pagination
              key={Number(123)}
              className="pagination"
              current={this.state.page}
              showQuickJumper={{ goButton: true }}
              showSizeChanger={true}
              pageSize={this.state.limit}
              pageSizeOptions={['10', '20', '50']}
              total={this.state.total}
              onChange={(page, size) => {
                this.onSearchChange({ page, limit: size });
              }}
            />
          )}
        </CardWrapper>
      </div>
    );
  }
}

export default Vul;
